#!/bin/sh /etc/rc.common
# Copyright (C) 2008 OpenWrt.org
START=96
USE_PROCD=1

compute_seconds() {
	local interval="$1"
	local unit="$2"

	if [ -z "$interval" ]
	then
		interval=10
	fi

	if [ -z "$unit" ]
	then
		unit="minutes"
	fi

	# compute interval in seconds
	case "$unit" in
		"days" )
			interval_seconds=$(($interval*60*60*24))
			;;
		"hours" )
			interval_seconds=$(($interval*60*60))
			;;
		"minutes" )
			interval_seconds=$(($interval*60))
			;;
		"seconds" )
			interval_seconds=$interval
			;;
		* )
			# default is minutes
			interval_seconds=$(($interval*60))
			;;
	esac

	echo $interval_seconds
}

append_item() {
	local section="$1"
	config_get_bool "enabled" "$section" "enabled" '0'
	[ "$enabled" -gt 0 ] && {
		config_get "disk" "$section" "disk"
		config_get "interval" "$section" "idle_time_interval"
		config_get "unit" "$section" "idle_time_unit"

		append args "-a $disk -i $(compute_seconds $interval $unit)"
	}
}

reload_service() {
	restart_service
}

service_triggers() {
	procd_add_reload_trigger "hdidle"
}

start_service() {
	args=""
	config_load "hdidle"
	config_foreach append_item device

	[ -n "$args" ] && {
		procd_open_instance
		procd_set_param command /usr/bin/hdidle -n $args
		procd_set_param respawn
		procd_close_instance
	}
}
